package com.gzs.learn.payment.pay.action;

import com.gzs.learn.common.util.SpringContextUtil;
import com.gzs.learn.inf.BaseResponseDto;
import com.gzs.learn.payment.inf.dto.web.PaymentChannel;
import com.gzs.learn.payment.inf.enums.OrderFromEnum;
import com.gzs.learn.payment.mapper.PaymentMapper;
import com.gzs.learn.payment.mapper.PaymentRefundMapper;
import com.gzs.learn.payment.model.po.Payment;
import com.gzs.learn.payment.model.po.PaymentRefund;
import com.gzs.learn.payment.pay.ContextBase;
import com.gzs.learn.payment.pay.PaymentContext;
import com.gzs.learn.payment.pay.PaymentSubTypeEnum;
import com.gzs.learn.payment.pay.PaymentTypeEnum;
import com.gzs.learn.payment.service.IPaymentChannelConfigService;

public abstract class BaseAction {

    public abstract BaseResponseDto<?> executeAction(PaymentContext<ContextBase> context);

    protected void initBaseContext(PaymentContext<ContextBase> context) {
        ContextBase contextObject = context.getContextObject();
        // 退款情形优先查询退款逆向的交易信息
        if (contextObject.getRefundSerial() != null && contextObject.getRefundSerial() > 0) {
            PaymentRefundMapper paymentRefundMapper = SpringContextUtil.getBean(PaymentRefundMapper.class);
            PaymentRefund paymentRefund = paymentRefundMapper.selectById(contextObject.getRefundSerial());
            contextObject.setSerial(paymentRefund.getSerial());
        }
        initPayment(context);
        initPaymentType(context);
    }

    protected void initPayment(PaymentContext<ContextBase> context) {
        ContextBase contextObject = context.getContextObject();
        if (contextObject.getSerial() == null) {
            return;
        }
        PaymentMapper paymentMapper = SpringContextUtil.getBean(PaymentMapper.class);
        // 查询正向的交易信息
        Payment payment = paymentMapper.selectById(contextObject.getSerial());
        if (payment != null) {
            contextObject.setAmt(payment.getAmt());
            contextObject.setChannel(payment.getChannel());
            contextObject.setMemberId(payment.getMemberId());
            contextObject.setOrderId(payment.getOrderId());
            contextObject.setOrderFrom(OrderFromEnum.convert(payment.getOrderFrom()));
        }
    }

    protected void initPaymentType(PaymentContext<ContextBase> context) {
        ContextBase contextObject = context.getContextObject();
        if (contextObject.getChannel() == null) {
            return;
        }
        IPaymentChannelConfigService configService = SpringContextUtil.getBean(IPaymentChannelConfigService.class);
        PaymentChannel paymentChannel = configService.getByChannelId(contextObject.getChannel());
        if (paymentChannel != null) {
            context.setPaymentTypeEnum(PaymentTypeEnum.convert(paymentChannel.getPaymentType()));
            context.setPaymentSubTypeEnum(PaymentSubTypeEnum.convert(paymentChannel.getPaymentSubType()));
        }
    }
}
